<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f2f5;
            color: #333;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: auto;
            background: white;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        h2 {
            text-align: center;
            color: #007bff;
            margin-bottom: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .user-info {
            font-size: 16px;
            color: #555;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f9f9f9;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        .btn {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        .form-group input {
            width: calc(100% - 20px);
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .search-container {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            gap: 10px;
        }
        .search-input {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            width: 70%;
            flex-grow: 1;
        }
        .search-btn {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .search-btn:hover {
            background-color: #218838;
        }
        .error-message {
            color: red;
            margin-top: 10px;
        }
        .custom-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 8px;
            z-index: 1000;
        }
        .success-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            background-color: #d4edda;
            color: #155722;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 5px;
            z-index: 1001;
        }
        .expired-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            background-color: #fff3cd;
            color: #856404;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 5px;
            z-index: 1001;
            text-align: center;
        }
        .expired-modal p {
            margin: 0 0 15px 0;
        }
        .expired-modal .btn {
            background-color: #ffc107;
        }
        .expired-modal .btn:hover {
            background-color: #e0a800;
        }
        .forbidden-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            background-color: #f8d7da;
            color: #721c24;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            border-radius: 5px;
            z-index: 1001;
            text-align: center;
        }
        .forbidden-modal p {
            margin: 0 0 15px 0;
        }
        .forbidden-modal .btn {
            background-color: #dc3545;
        }
        .forbidden-modal .btn:hover {
            background-color: #c82333;
        }
        .close {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        #overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background-color: rgba(0,0,0,0.5);
            z-index: 999;
            display: none;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h2>用户管理</h2>
        <div class="user-info">
            欢迎，<span id="username"></span>！ <button class="btn" id="logout-btn">退出登录</button>
        </div>
    </div>

    <div class="search-container">
        <input type="text" id="search-keywords" class="search-input" placeholder="输入关键字进行搜索">
        <button class="search-btn" onclick="fetchUsers()">搜索</button>
        <button class="btn" onclick="openAddModal()">新增用户</button>
    </div>

    <table id="user-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div id="addCustomModal" class="custom-modal">
        <span id="closeAdd" class="close">×</span>
        <h2>新增用户</h2>
        <div id="add-error-message" class="error-message"></div>
        <form id="add-form">
            <div class="form-group">
                <label for="add-username">用户名</label>
                <input type="text" id="add-username" required>
            </div>
            <div class="form-group">
                <label for="add-email">邮箱</label>
                <input type="email" id="add-email" required>
            </div>
            <button type="submit" class="btn">新增用户</button>
        </form>
    </div>

    <div id="editCustomModal" class="custom-modal">
        <span id="closeEdit" class="close">×</span>
        <h2>编辑用户</h2>
        <div id="error-message" class="error-message"></div>
        <form id="edit-form">
            <input type="hidden" id="edit-id">
            <div class="form-group">
                <label for="edit-username">用户名</label>
                <input type="text" id="edit-username" required>
            </div>
            <div class="form-group">
                <label for="edit-email">邮箱</label>
                <input type="email" id="edit-email" required>
            </div>
            <button type="submit" class="btn">保存更改</button>
        </form>
    </div>

    <div id="successModal" class="success-modal">
        <span id="closeSuccess" class="close">×</span>
        <p id="successMessage"></p>
    </div>

    <div id="expiredModal" class="expired-modal">
        <p>登录已过期，请重新登录</p>
        <button class="btn" id="expiredConfirm">确定</button>
    </div>

    <div id="forbiddenModal" class="forbidden-modal">
        <p>当前登录已过期，请重新登录</p>
        <button class="btn" id="forbiddenConfirm">确定</button>
    </div>

    <div id="overlay"></div>
</div>

<script>
    var currentModalId = null;
    var overlay = document.getElementById('overlay');
    var successModal = document.getElementById('successModal');
    var successMessage = document.getElementById('successMessage');
    var expiredModal = document.getElementById('expiredModal');
    var expiredConfirm = document.getElementById('expiredConfirm');
    var forbiddenModal = document.getElementById('forbiddenModal');
    var forbiddenConfirm = document.getElementById('forbiddenConfirm');
    const token = localStorage.getItem('token');

    // 检查登录状态，未登录直接跳转
    if (!token) {
        window.location.href = 'http://localhost:8080/login.html';
    } else {
        const username = localStorage.getItem('username');
        document.getElementById('username').textContent = username || '用户';
    }

    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', function() {
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        window.location.href = 'http://localhost:8080/login.html';
    });

    // 显示登录过期弹窗 (401)
    function showExpiredModal() {
        expiredModal.style.display = 'block';
        overlay.style.display = 'block';
    }

    // 显示403禁止访问弹窗
    function showForbiddenModal() {
        forbiddenModal.style.display = 'block';
        overlay.style.display = 'block';
    }

    // 关闭登录过期弹窗并跳转 (401)
    expiredConfirm.addEventListener('click', function() {
        redirectToLogin();
    });

    // 关闭403弹窗并跳转
    forbiddenConfirm.addEventListener('click', function() {
        redirectToLogin();
    });

    // 跳转到登录页的通用函数
    function redirectToLogin() {
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        window.location.href = 'http://localhost:8080/login.html';
    }

    // 获取所有用户
    function fetchUsers() {
        const keywords = document.getElementById('search-keywords').value.trim();
        const requestBody = {
            id: '',
            username: '',
            email: '',
            keyWords: keywords || ''
        };

        fetch('/users/all', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestBody)
        })
            .then(response => {
                if (response.status === 401) {
                    showExpiredModal();
                    return;
                }
                if (response.status === 403) {
                    showForbiddenModal();
                    return;
                }
                return response.json();
            })
            .then(responseBody => {
                if (responseBody && responseBody.code === 200) {
                    populateTable(responseBody.data);
                } else {
                    console.error('Error:', responseBody ? responseBody.message : 'No response body');
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
            });
    }

    // 填充表格
    function populateTable(users) {
        const tbody = document.querySelector('#user-table tbody');
        tbody.innerHTML = '';
        users.forEach(user => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>
                    <button class="btn" onclick="openEditModal('${user.id}', '${user.username}', '${user.email}')">编辑</button>
                    <button class="btn" style="background-color: #dc3545; margin-left: 10px;" onclick="deleteUser('${user.id}')">删除</button>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 删除用户
    function deleteUser(id) {
        if (!confirm('确定要删除此用户吗？')) {
            return;
        }

        const requestBody = {
            id: id
        };

        fetch('/users/delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestBody)
        })
            .then(response => {
                if (response.status === 401) {
                    showExpiredModal();
                    return;
                }
                if (response.status === 403) {
                    showForbiddenModal();
                    return;
                }
                return response.json();
            })
            .then(responseBody => {
                if (responseBody && responseBody.code === 200) {
                    showSuccess('用户删除成功');
                    fetchUsers();
                } else {
                    alert(responseBody ? responseBody.message : '删除失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生了一个错误，请稍后再试。');
            });
    }

    // 打开新增用户弹窗
    function openAddModal() {
        currentModalId = 'addCustomModal';
        document.getElementById('addCustomModal').style.display = 'block';
        overlay.style.display = 'block';
    }

    // 打开编辑用户弹窗
    function openEditModal(id, username, email) {
        currentModalId = 'editCustomModal';
        document.getElementById('edit-id').value = id;
        document.getElementById('edit-username').value = username;
        document.getElementById('edit-email').value = email;
        document.getElementById('editCustomModal').style.display = 'block';
        overlay.style.display = 'block';
    }

    // 关闭新增用户弹窗
    function closeAddModal() {
        document.getElementById('addCustomModal').style.display = 'none';
        overlay.style.display = 'none';
        document.getElementById('add-username').value = '';
        document.getElementById('add-email').value = '';
        document.getElementById('add-error-message').textContent = '';
    }

    // 关闭编辑用户弹窗
    function closeModal() {
        document.getElementById('editCustomModal').style.display = 'none';
        overlay.style.display = 'none';
        document.getElementById('error-message').textContent = '';
    }

    // 显示成功提示弹窗
    function showSuccess(message) {
        successMessage.textContent = message;
        successModal.style.display = 'block';
        setTimeout(() => {
            closeSuccess();
        }, 3000);
    }

    // 关闭成功提示弹窗
    function closeSuccess() {
        successModal.style.display = 'none';
    }

    // 新增用户信息
    document.getElementById('add-form').addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('add-username').value.trim();
        const email = document.getElementById('add-email').value.trim();

        const requestBody = {
            username: username,
            email: email
        };

        fetch('/users/insert', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestBody)
        })
            .then(response => {
                if (response.status === 401) {
                    showExpiredModal();
                    return;
                }
                if (response.status === 403) {
                    showForbiddenModal();
                    return;
                }
                return response.json();
            })
            .then(responseBody => {
                if (responseBody && responseBody.code === 200) {
                    showSuccess('用户新增成功');
                    closeAddModal();
                    fetchUsers();
                } else {
                    document.getElementById('add-error-message').textContent = responseBody ? responseBody.message : '新增失败';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('add-error-message').textContent = '发生了一个错误，请稍后再试。';
            });
    });

    // 更新用户信息
    document.getElementById('edit-form').addEventListener('submit', function(event) {
        event.preventDefault();
        const id = document.getElementById('edit-id').value;
        const username = document.getElementById('edit-username').value;
        const email = document.getElementById('edit-email').value;

        const requestBody = {
            id: parseInt(id),
            username: username,
            email: email
        };

        fetch('/users/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestBody)
        })
            .then(response => {
                if (response.status === 401) {
                    showExpiredModal();
                    return;
                }
                if (response.status === 403) {
                    showForbiddenModal();
                    return;
                }
                return response.json();
            })
            .then(responseBody => {
                if (responseBody && responseBody.code === 200) {
                    showSuccess('用户信息更新成功');
                    closeModal();
                    fetchUsers();
                } else {
                    document.getElementById('error-message').textContent = responseBody ? responseBody.message : '更新失败';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('error-message').textContent = '发生了一个错误，请稍后再试。';
            });
    });

    // 关闭按钮事件
    document.getElementById('closeAdd').addEventListener('click', function() {
        closeAddModal();
    });

    document.getElementById('closeEdit').addEventListener('click', function() {
        closeModal();
    });

    document.getElementById('closeSuccess').addEventListener('click', function() {
        closeSuccess();
    });

    // 点击覆盖层关闭弹窗
    window.onclick = function(event) {
        if (event.target == overlay && currentModalId) {
            if (currentModalId === 'addCustomModal') {
                closeAddModal();
            } else if (currentModalId === 'editCustomModal') {
                closeModal();
            }
        }
    };

    // 初始化加载用户数据（仅在登录时执行）
    if (token) {
        fetchUsers();
    }
</script>
</body>
</html>